package com.lsyw.intergrate.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lsyw.intergrate.common.Result;
import com.lsyw.intergrate.common.util.DateUtil;
import com.lsyw.intergrate.entity.*;
import com.lsyw.intergrate.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import static com.lsyw.intergrate.common.Result.errorResult;

/**
 * <p>
 * 移动端前端控制器
 * </p>
 *
 * @author 刘磊
 * @since 2023-04-18
 */
@Api(tags = "大屏接口")
@RestController
@RequestMapping("/dp")
public class DpController {


    @Autowired
    private MassifService massifService;

    @Autowired
    private MassifRecordService massifRecordService;
    @Autowired
    private JcMassifFactorValueLogService jcMassifFactorValueLogService;
    @Autowired
    private JcMassifFactorValueService jcMassifFactorValueService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private JcFactorService jcFactorService;
    @Autowired
    private TransportWorkOrderService transportWorkOrderService;
    @Autowired
    private MSamplingTaskDetectionService mSamplingTaskDetectionService;

    /**
     * 工地修复进度
     */
    @GetMapping("/getMassifProgress")
    @ApiOperation(value = "工地修复进度", notes = "工地修复进度", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "massifId", value = "地块id", required = true, paramType = "query", dataType = "String")
    })
    public Result getMassifProgress(String massifId) {
        Massif massif = massifService.getById(massifId);
        final LambdaQueryWrapper<MassifRecord> lambda = new QueryWrapper<MassifRecord>().lambda();
        //TODO 自己的查询逻辑
        lambda.like(MassifRecord::getMassifId, massifId);
        lambda.eq(MassifRecord::getDelFlag, 0);
        List<MassifRecord> list = massifRecordService.list(lambda);
        Double initHeat = list.stream().mapToDouble(MassifRecord::getInitHeat).sum();
        Double otherHeat = list.stream().mapToDouble(MassifRecord::getOtherHeat).sum();
        Double kilnNum = list.stream().mapToDouble(MassifRecord::getKilnNum).sum();
        Double soilEpair = list.stream().mapToDouble(MassifRecord::getSoilEpair).sum();
        Double pretreatment = list.stream().mapToDouble(MassifRecord::getPretreatment).sum();
        Double groundWater = list.stream().mapToDouble(MassifRecord::getGroundWater).sum();
        List<Map<String, Object>> mapList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("name", "土壤预处理");
        map.put("total", massif.getTrycl());
        map.put("value", pretreatment);
        mapList.add(map);
        Map<String, Object> map1 = new HashMap<>();
        map1.put("name", "原位土壤修复");
        map1.put("total", massif.getYwtrxfl());
        map1.put("value", initHeat);
        mapList.add(map1);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("name", "异位土壤修复");
        map2.put("total", massif.getYwtrxfl());
        map2.put("value", otherHeat);
        mapList.add(map2);
        Map<String, Object> map3 = new HashMap<>();
        map3.put("name", "协同处置修复");
        map3.put("total", massif.getXtczxfl());
        map3.put("value", kilnNum);
        mapList.add(map3);
        Map<String, Object> map4 = new HashMap<>();
        map4.put("name", "地下水修复");
        map4.put("total", massif.getDxsxfl());
        map4.put("value", groundWater);
        mapList.add(map4);
        Map<String, Object> map5 = new HashMap<>();
        map5.put("name", "土壤修复总进度");
        map5.put("total", massif.getTrxfzfl());
        map5.put("value", soilEpair);
        mapList.add(map5);
        return Result.successResult(mapList);
    }

    /**
     * 工地修复进度
     */
    @GetMapping("/getMassifAllProgress")
    @ApiOperation(value = "工地修复总进度", notes = "工地修复总进度", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "massifId", value = "地块id", required = true, paramType = "query", dataType = "String")
    })
    public Result getMassifAllProgress(String massifId) {
        Massif massif = massifService.getById(massifId);
        final LambdaQueryWrapper<MassifRecord> lambda = new QueryWrapper<MassifRecord>().lambda();
        //TODO 自己的查询逻辑
        lambda.like(MassifRecord::getMassifId, massifId);
        lambda.eq(MassifRecord::getDelFlag, 0);
        List<MassifRecord> list = massifRecordService.list(lambda);
        Double soilEpair = list.stream().mapToDouble(MassifRecord::getSoilEpair).sum();
        Double groundWater = list.stream().mapToDouble(MassifRecord::getGroundWater).sum();
        Map<String, Double> map = new HashMap<>();
        map.put("地下水修复", (groundWater / massif.getDxsxfl()) * 100);
        map.put("土壤修复总进度", (soilEpair / massif.getTrxfzfl()) * 100);
        map.put("工程修复总进度", ((soilEpair / massif.getTrxfzfl()) * 100 + (groundWater / massif.getDxsxfl()) * 100) / 2);
        return Result.successResult(map);
    }

    /**
     * 工地实时大气环境数据
     */
    @GetMapping("/getMassifEnvironment")
    @ApiOperation(value = "工地实时大气环境数据", notes = "工地实时大气环境数据", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "massifId", value = "地块id", required = true, paramType = "query", dataType = "String")
    })
    public Result getMassifEnvironment(String massifId) {
        String cn = "2011";
        JcMassifFactorValueLog jcMassifFactorValueLog = jcMassifFactorValueLogService.getOneByMassif(massifId, cn);
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (jcMassifFactorValueLog != null) {
            final LambdaQueryWrapper<JcMassifFactorValue> lambda2 = new QueryWrapper<JcMassifFactorValue>().lambda();
            lambda2.eq(JcMassifFactorValue::getDelFlag, 0);
            lambda2.eq(JcMassifFactorValue::getJcMassifFactorValueLog, jcMassifFactorValueLog.getId());
            lambda2.isNotNull(JcMassifFactorValue::getValue);
            List<JcMassifFactorValue> list2 = jcMassifFactorValueService.list(lambda2);

            list2.forEach(k -> {
                Map<String, Object> map = new HashMap<>();
                JcFactor jcFactor = jcFactorService.getById(k.getJcFactorId());
                map.put("name", jcFactor.getName());
                map.put("unit", jcFactor.getUnitMeasurement());
                map.put("value", k.getValue());
                mapList.add(map);
            });
        }

        return Result.successResult(mapList);
    }

    /**
     * 转运记录
     */
    @GetMapping("/transportList")
    @ApiOperation(value = "转运记录", notes = "转运记录", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "massifId", value = "地块id", required = true, paramType = "query", dataType = "String")
    })
    public Result transportList(String massifId) {
        Date startTime = DateUtil.getStartTime(DateUtil.addDays(new Date(), -6));
        Date endTime = DateUtil.getDayEndTime(new Date());
        Map<String, Object> map = new HashMap<>();
        map.put("massifId", massifId);
        map.put("startTime", startTime);
        map.put("endTime", endTime);

        List<Map<String, Object>> list = transportWorkOrderService.getValueByDqy(map);
        Map<String, Object> mapValue = new HashMap<>();
        list.forEach(e -> {
            mapValue.put(e.get("date").toString(), e.get("value"));
        });
        Date fromDate = startTime;
        Map<String, Object> mapFrom = new HashMap<>();
        List<Object> listX = new ArrayList<>();
        List<Object> listY = new ArrayList<>();
        while (fromDate.compareTo(endTime) < 1) {
            listX.add(DateUtil.format(fromDate));
            if (mapValue.get(DateUtil.format(fromDate)) != null) {
                listY.add(mapValue.get(DateUtil.format(fromDate)));
            } else {
                listY.add(0);
            }
            fromDate = DateUtil.addDays(fromDate, 1);
        }
        mapFrom.put("listX", listX);
        mapFrom.put("listY", listY);


        return Result.successResult(mapFrom);
    }

    /**
     * 转运记录
     */
    @GetMapping("/MSampling_hjkq")
    @ApiOperation(value = "检测因子达标率-环境空气", notes = "检测因子达标率-环境空气", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "massifId", value = "地块id", required = true, paramType = "query", dataType = "String")
    })
    public Result MSampling_hjkq(String massifId) {

        List<Map<String, Object>> list = mSamplingTaskDetectionService.getValueByTypeAndMassifId(3, massifId);
        Map<String, Object> mapFrom = new HashMap<>();
        List<Object> listX = new ArrayList<>();
        List<Object> listY = new ArrayList<>();
        list.forEach(e -> {
            listX.add(e.get("date"));
            listY.add(e.get("value"));
        });

        mapFrom.put("listX", listX);
        mapFrom.put("listY", listY);


        return Result.successResult(mapFrom);
    }


    /**
     * 转运记录
     */
    @GetMapping("/MSampling_dbs")
    @ApiOperation(value = "检测因子达标率-地表水", notes = "检测因子达标率-地表水", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "massifId", value = "地块id", required = true, paramType = "query", dataType = "String")
    })
    public Result MSampling_dbs(String massifId) {

        List<Map<String, Object>> list = mSamplingTaskDetectionService.getValueByTypeAndMassifId(2, massifId);
        Map<String, Object> mapFrom = new HashMap<>();
        List<Object> listX = new ArrayList<>();
        List<Object> listY = new ArrayList<>();
        list.forEach(e -> {
            listX.add(e.get("date"));
            listY.add(e.get("value"));
        });

        mapFrom.put("listX", listX);
        mapFrom.put("listY", listY);


        return Result.successResult(mapFrom);
    }

    /**
     * 转运记录
     */
    @GetMapping("/MSampling_tr")
    @ApiOperation(value = "检测因子达标率-土壤", notes = "检测因子达标率-土壤", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "massifId", value = "地块id", required = true, paramType = "query", dataType = "String")
    })
    public Result MSampling_tr(String massifId) {

        List<Map<String, Object>> list = mSamplingTaskDetectionService.getValueByTypeAndMassifId(1, massifId);
        Map<String, Object> mapFrom = new HashMap<>();
        List<Object> listX = new ArrayList<>();
        List<Object> listY = new ArrayList<>();
        list.forEach(e -> {
            listX.add(e.get("date"));
            listY.add(e.get("value"));
        });

        mapFrom.put("listX", listX);
        mapFrom.put("listY", listY);


        return Result.successResult(mapFrom);
    }

    /**
     * 转运记录
     */
    @GetMapping("/pollution_prevention_and_control")
    @ApiOperation(value = "二次污染防控", notes = "二次污染防控", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceId", value = "设备id", required = true, paramType = "query", dataType = "String")
    })
    public Result pollution_prevention_and_control(String deviceId) {
        JSONObject dataJson = new JSONObject();
        Device device = deviceService.getById(deviceId);
        List<JcFactor> jcFactorList = jcFactorService.getListByDeviceId(deviceId);
        List<String> cnList = new ArrayList<>();
        cnList.add("2061");
        String format = "HH";
        final LambdaQueryWrapper<JcMassifFactorValueLog> lambda = new QueryWrapper<JcMassifFactorValueLog>().lambda();
        lambda.in(JcMassifFactorValueLog::getCn, cnList);
        lambda.eq(JcMassifFactorValueLog::getDelFlag, 0);
        lambda.between(JcMassifFactorValueLog::getGmtCreate, DateUtil.addHour(new Date(), -24), new Date());
        lambda.eq(JcMassifFactorValueLog::getDeviceNo, device.getCode());
        lambda.orderByDesc(JcMassifFactorValueLog::getGmtCreate);
        List<JcMassifFactorValueLog> list = this.jcMassifFactorValueLogService.list(lambda);
        List<JSONObject> factorStackedLineChartList = new ArrayList<>();
        List<Map<String, Object>> bodyList = new ArrayList<>();
        List<String> dateTrendList = new ArrayList<>();
        list.forEach(e -> {
            Map<String, Object> map = new HashMap<>();
            final LambdaQueryWrapper<JcMassifFactorValue> lambda2 = new QueryWrapper<JcMassifFactorValue>().lambda();
            lambda2.eq(JcMassifFactorValue::getDelFlag, 0);
            lambda2.eq(JcMassifFactorValue::getJcMassifFactorValueLog, e.getId());
            lambda2.isNotNull(JcMassifFactorValue::getValue);
            List<JcMassifFactorValue> list2 = jcMassifFactorValueService.list(lambda2);
            jcFactorList.forEach(k -> {
                Optional<JcMassifFactorValue> mapOptional = list2.stream().filter(b -> (
                                b.getJcFactorId().equals(k.getId())
                        )
                ).findFirst();
                if (mapOptional.isPresent()) {
                    JcMassifFactorValue jcMassifFactorValue = mapOptional.get();
                    map.put(k.getId(), jcMassifFactorValue.getValue());
                } else {
                    map.put(k.getId(), 0);
                }
            });
            dateTrendList.add(DateUtil.format(e.getGmtCreate(), format));
            bodyList.add(map);
        });
        jcFactorList.forEach(e -> {
            JSONObject jcFactorJson = new JSONObject();
            jcFactorJson.put("factorName", e.getName());
            jcFactorJson.put("unit", e.getUnitMeasurement());
            List<String> valueList = new ArrayList<>();
            bodyList.forEach(k -> {
                if (k.get(e.getId()) != null) {
                    valueList.add(k.get(e.getId()) + "");
                } else {
                    valueList.add("0");
                }
            });

            jcFactorJson.put("data", recursiveReverse(valueList));
            factorStackedLineChartList.add(jcFactorJson);


        });
        dataJson.put("factorStackedLineChartList", factorStackedLineChartList);
        dataJson.put("dateTrendList", recursiveReverse(dateTrendList));
        return Result.successResult(dataJson);
    }

    private static List recursiveReverse(List list) {
        if (list.isEmpty()) {
            return new ArrayList<>();
        } else {
            List reversedList = recursiveReverse(list.subList(1, list.size()));
            reversedList.add(list.get(0));
            return reversedList;
        }
    }

    /**
     * 转运记录
     */
    @GetMapping("/getDevice")
    @ApiOperation(value = "获取工地下设备", notes = "获取工地下设备", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "massifId", value = "地块id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "types", value = "设备类型，多个以,隔开", required = true, paramType = "query", dataType = "String")
    })
    public Result getDevice(String massifId, String types) {

        final LambdaQueryWrapper<Device> lambda = new QueryWrapper<Device>().lambda();
        lambda.eq(Device::getDelFlag, 0);
        lambda.eq(Device::getMassifId, massifId);
        List<String> list = Arrays.asList(types.split(","));
        lambda.in(Device::getType, list);
        return Result.successResult(deviceService.list(lambda));
    }

    /**
     * 设备每日峰值
     */
    @ApiOperation(value = "热力图")
    @PostMapping("/heatMap")
    public Result heatMap_air(@RequestBody Map<String, Object> condition) {
        if (condition.get("massifId") == null || condition.get("massifId").toString().equals("")) {
            return Result.errorResult("项目id为空");
        }
        condition.put("startTime", DateUtil.formatTime(DateUtil.addDays(new Date(), -1)));
        condition.put("endTime", DateUtil.formatTime(new Date()));

        final LambdaQueryWrapper<Device> lambda = new QueryWrapper<Device>().lambda();
        //TODO 自己的查询逻辑
        lambda.eq(Device::getMassifId, condition.get("massifId").toString());
        if (condition.get("type").toString().equals("1")) {
            lambda.eq(Device::getType, "13");
        } else if (condition.get("type").toString().equals("2")) {
            lambda.eq(Device::getType, "17");
        }

        List<Device> list = deviceService.list(lambda);
        List<Map<String, Object>> mapList = new ArrayList<>();
        list.forEach(e -> {
            Map<String, Object> map = new HashMap<>();
            map.put("lng", e.getXId());
            map.put("lat", e.getYId());
            int count = 0;
            condition.put("deviceNo", e.getCode());
            List<Map<String, Object>> list2 = jcMassifFactorValueService.getAvgInfo(condition);
            Map<String, Object> mapData = new HashMap<>();
            list2.forEach(k -> {
                mapData.put(k.get("jcFactorId").toString(), k.get("avgValue"));
            });

            if (condition.get("type").toString().equals("1")) {
                if (mapData.get("a34002") != null && mapData.get("a34004") == null) {
                    count = calculateAQI_PM10(Double.parseDouble(mapData.get("a34002").toString()));
                } else if (mapData.get("a34002") == null && mapData.get("a34004") != null) {
                    count = calculateAQI_PM25(Double.parseDouble(mapData.get("a34004").toString()));
                } else if (mapData.get("a34002") != null && mapData.get("a34004") != null) {
                    count = calculateAQI(Double.parseDouble(mapData.get("a34002").toString()), Double.parseDouble(mapData.get("a34004").toString()));
                }
            } else if (condition.get("type").toString().equals("2")) {
            }


            map.put("count", count);
            mapList.add(map);
        });

        return Result.successResult(mapList);
    }

    // 根据PM10浓度计算对应的AQI值
    public static int calculateAQI_PM10(double pm10) {
        double[] breakpoints = {0, 50, 150, 250, 350, 420, 500};
        double[] aqiValues = {0, 50, 100, 150, 200, 300, 500};
        return calculateAQI(pm10, breakpoints, aqiValues);
    }

    // 根据PM2.5浓度计算对应的AQI值
    public static int calculateAQI_PM25(double pm25) {
        double[] breakpoints = {0, 35, 75, 115, 150, 250, 350};
        double[] aqiValues = {0, 50, 100, 150, 200, 300, 400};
        return calculateAQI(pm25, breakpoints, aqiValues);
    }

    // 根据浓度值和分段点和对应AQI值计算AQI值
    public static int calculateAQI(double concentration, double[] breakpoints, double[] aqiValues) {
        double result = 0;

        for (int i = 0; i < breakpoints.length - 1; i++) {
            if (concentration >= breakpoints[i] && concentration <= breakpoints[i + 1]) {
                result = ((aqiValues[i + 1] - aqiValues[i]) / (breakpoints[i + 1] - breakpoints[i])) * (concentration - breakpoints[i]) + aqiValues[i];
                break;
            }
        }

        return (int) Math.ceil(result);
    }

    // 计算AQI
    public static int calculateAQI(double pm10, double pm25) {
        double aqi = 0;

        // 计算PM10和PM2.5的AQI
        double aqiPM10 = calculateAQI_PM10(pm10);
        double aqiPM25 = calculateAQI_PM25(pm25);

        // 取较大的AQI作为最终结果
        if (aqiPM10 > aqiPM25) {
            aqi = aqiPM10;
        } else {
            aqi = aqiPM25;
        }

        return (int) aqi;
    }


    @GetMapping("/monitorDevice")
    @ApiOperation(value = "检测站点", notes = "检测站点", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "massifId", value = "地块id", required = true, paramType = "query", dataType = "String")
    })
    public Result monitorDevice(String massifId) {

        List<Map<String, Object>> list = new ArrayList<>();
        List<String> deviceNoList = jcMassifFactorValueService.getDeviceNoList(massifId, DateUtil.addHour(new Date(), -1), new Date());
        final LambdaQueryWrapper<Device> lambda = new QueryWrapper<Device>().lambda();
        lambda.eq(Device::getDelFlag, 0);
        lambda.eq(Device::getMassifId, massifId);
        lambda.eq(Device::getType, "17");
        List<Device> waterList = deviceService.list(lambda);
        AtomicInteger onlineWater = new AtomicInteger();
        waterList.forEach(e -> {
            if (deviceNoList.contains(e.getCode())) {
                onlineWater.getAndIncrement();
            }
        });
        Map<String, Object> water = new HashMap<>();
        water.put("name", "水质监测站");
        water.put("allCount", waterList.size());
        water.put("onlineCount", onlineWater.intValue());
        list.add(water);
        final LambdaQueryWrapper<Device> lambdaA = new QueryWrapper<Device>().lambda();
        lambdaA.eq(Device::getDelFlag, 0);
        lambdaA.eq(Device::getMassifId, massifId);
        lambdaA.eq(Device::getType, "13");
        List<Device> airList = deviceService.list(lambdaA);
        AtomicInteger airWater = new AtomicInteger();
        airList.forEach(e -> {
            if (deviceNoList.contains(e.getCode())) {
                airWater.getAndIncrement();
            }
        });
        Map<String, Object> air = new HashMap<>();
        air.put("name", "大气监测站");
        air.put("allCount", airList.size());
        air.put("onlineCount", airWater.intValue());
        list.add(air);
        Map<String, Object> sound = new HashMap<>();
        sound.put("name", "噪声监测站");
        sound.put("allCount", airList.size());
        sound.put("onlineCount", airWater.intValue());
        list.add(sound);


        return Result.successResult(list);
    }


    @GetMapping("/airQualityTrend")
    @ApiOperation(value = "空气质量变化趋势", notes = "空气质量变化趋势", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "massifId", value = "地块id", required = true, paramType = "query", dataType = "String")
    })
    public Result airQualityTrend(String massifId) {
        Date fromDate = DateUtil.addDays(new Date(), -6);
        Date endTime = new Date();
        Map<String, Object> mapFrom = new HashMap<>();
        List<Object> listX = new ArrayList<>();
        List<Object> listY = new ArrayList<>();


        while (fromDate.compareTo(endTime) < 1) {
            Map<String, Object> condition = new HashMap<>();
            condition.put("startTime", DateUtil.formatTime(DateUtil.getStartTime(fromDate)));
            condition.put("endTime", DateUtil.formatTime(DateUtil.getEndTime(fromDate)));
            condition.put("massifId", massifId);

            final LambdaQueryWrapper<Device> lambda = new QueryWrapper<Device>().lambda();
            //TODO 自己的查询逻辑
            lambda.eq(Device::getMassifId, massifId);
            lambda.eq(Device::getType, "13");

            List<Device> list = deviceService.list(lambda);
            List<Integer> values = new ArrayList<>();
            list.forEach(e -> {
                int count = 0;
                condition.put("deviceNo", e.getCode());
                List<Map<String, Object>> list2 = jcMassifFactorValueService.getAvgInfo(condition);
                Map<String, Object> mapData = new HashMap<>();
                list2.forEach(k -> {
                    mapData.put(k.get("jcFactorId").toString(), k.get("avgValue"));
                });

                if (mapData.get("a34002") != null && mapData.get("a34004") == null) {
                    count = calculateAQI_PM10(Double.parseDouble(mapData.get("a34002").toString()));
                } else if (mapData.get("a34002") == null && mapData.get("a34004") != null) {
                    count = calculateAQI_PM25(Double.parseDouble(mapData.get("a34004").toString()));
                } else if (mapData.get("a34002") != null && mapData.get("a34004") != null) {
                    count = calculateAQI(Double.parseDouble(mapData.get("a34002").toString()), Double.parseDouble(mapData.get("a34004").toString()));
                }
                values.add(count);
            });
            listX.add(DateUtil.format(fromDate));
            if (values.size() > 0) {
                listY.add(values.stream()
                        .mapToInt(Integer::intValue)
                        .average()
                        .getAsDouble());
            } else {
                listY.add(0);
            }
            fromDate = DateUtil.addDays(fromDate, 1);
        }
        mapFrom.put("listX", listX);
        mapFrom.put("listY", listY);

        return Result.successResult(mapFrom);
    }


    @GetMapping("/voiceQualityTrend")
    @ApiOperation(value = "声音质量变化趋势", notes = "声音质量变化趋势", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "massifId", value = "地块id", required = true, paramType = "query", dataType = "String")
    })
    public Result voiceQualityTrend(String massifId) {
        Date fromDate = DateUtil.addDays(new Date(), -6);
        Date endTime = new Date();
        Map<String, Object> mapFrom = new HashMap<>();
        List<Object> listX = new ArrayList<>();
        List<Object> listY = new ArrayList<>();
        final LambdaQueryWrapper<Device> lambda = new QueryWrapper<Device>().lambda();
        //TODO 自己的查询逻辑
        lambda.eq(Device::getMassifId, massifId);
        lambda.eq(Device::getType, "13");

        List<Device> list = deviceService.list(lambda);

        while (fromDate.compareTo(endTime) < 1) {
            Map<String, Object> condition = new HashMap<>();
            condition.put("startTime", DateUtil.formatTime(DateUtil.getStartTime(fromDate)));
            condition.put("endTime", DateUtil.formatTime(DateUtil.getEndTime(fromDate)));
            condition.put("massifId", massifId);


            List<Double> values = new ArrayList<>();
            list.forEach(e -> {
                condition.put("deviceNo", e.getCode());
                Map<String, Object> map = jcMassifFactorValueService.getAvgVoiceInfo(condition);
                values.add(map == null ? 0.0 : Double.parseDouble(map.get("avgValue").toString()));

            });
            listX.add(DateUtil.format(fromDate));
            if (values.size() > 0) {
                listY.add(values.stream()
                        .mapToDouble(Double::doubleValue)
                        .average()
                        .getAsDouble());
            } else {
                listY.add(0);
            }
            fromDate = DateUtil.addDays(fromDate, 1);
        }
        mapFrom.put("listX", listX);
        mapFrom.put("listY", listY);

        return Result.successResult(mapFrom);
    }


}
